﻿using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AirQuality
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private static Mutex mutex = null;
        public MainWindow()
        {
            InitializeComponent();


            bool isAppRunning = false;
            //设置一个名称为进程名的互斥体
            mutex = new Mutex(true, System.Diagnostics.Process.GetCurrentProcess().ProcessName, out isAppRunning);

            if (!isAppRunning)
            {
                //_ = MessageBox.Show("program has been opened");
                Application.Current.Shutdown(1);
            }

            MainViewModel mainViewModel = new MainViewModel(this);
            DataContext = mainViewModel;
            Server.SetFromFile();

            mainViewModel.SetLocation(Server.ConfigJson["location"].ToString());

            try
            {
                Server.serialPort.PortName = Server.ConfigJson["COM"].ToString();
                Server.serialPort.Open();
                Messenger.Default.Send(true, "SerialERR");
            }
            catch
            {
                Messenger.Default.Send(false, "SerialERR");
                Loaded += MainWindow_Loaded;
            }
            MouseLeftButtonDown += MainWindow_MouseLeftButtonDown;
            MouseLeftButtonUp += MainWindow_MouseLeftButtonUp;
            Server.SerialThread.Start();//启动串口线程
        }

        private void MainWindow_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Server.ConfigJson["x"] = Left;
            Server.ConfigJson["y"] = Top;
            Server.ConfigJson["location"] = "Custom";
        }

        private void MainWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            (DataContext as MainViewModel).SettingCommand.Execute(null);
        }
    }
}
